import { Button, Form, Grid, Space } from "@arco-design/web-react";
import "./index.scss";
import { useEffect, useState } from "react";
import { CustomFormPropsInt } from "./utils/types";
import { getFormItem } from "./utils/hooks";
import { withDefaults } from "@/types";
const FormItem = Form.Item;
const Row = Grid.Row;
const Col = Grid.Col;

export default function CustomForm(props: CustomFormPropsInt) {
  const [_form] = Form.useForm();
  const form = props.form ? props.form : _form;
  const [initialValue, setinitialValue] = useState<Record<string, any>>({});
  const _props = withDefaults(props, {
    showBtn: true,
  });

  const onReset = () => {
    form.setFieldsValue(initialValue);
    props.reset?.(initialValue);
  };

  useEffect(() => {
    const values: Record<string, any> = {};
    if (!props.formAttrs?.initialValues) {
      props.items.map((el) => {
        values[el.field!] = el.initialValue;
      });
      form.setFieldsValue(initialValue);
      setinitialValue(values);
    }
  }, [props.items]);

  return (
    <div className="custom-form">
      <Form
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        form={form}
        {...props.formAttrs}
      >
        <Row className="w-full">
          {props.items.map((item) => {
            return getFormItem(props, item);
          })}
          {_props.showBtn && (
            <Col span={props.wrap ? 24 : 4}>
              <FormItem>
                <Space>
                  <Button onClick={onReset}>重置</Button>
                  <Button type="primary" htmlType="submit">
                    搜索
                  </Button>
                </Space>
              </FormItem>
            </Col>
          )}
        </Row>
      </Form>
    </div>
  );
}
